package com.music.activity;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.music.R;
import com.music.VolumePopupWindow;
import com.music.utilbean.Constant;
import com.music.utilbean.MediaUtils;
import com.music.utilbean.Mp3Info;
import com.music.utilbean.ToUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 音乐播放器页面
 */
public class MusicPlayerActivity extends MusicBaseActivity implements OnClickListener, OnSeekBarChangeListener {
	private TextView title, begin_time, end_time;
	private ImageButton img_play, img_back, img_go, menu, img_lyric;

	private static final int UPDATE_TIME = 1;
	private static MyHandler              myHandler;
	private        ArrayList<Mp3Info>     mp3Infos;
	private        LrcView                mLrcView;
	private        int                    mDuration;
	private        ImageView              img_love;
	private        SeekBar                seekBar;
	private        DriverManager          manager;
	private        ImageButton            mBackBtn;
	private        ImageButton            mPlay_more_functions;
	private        RelativeLayout         mRootLayout;
	private        String                 mStr;
	private        boolean                mIsResume;
//	private        NewCallReceiver        mCallReceiver;
	private        SharedPreferences      mSp;
	private        WakeBroadcastReceiver1 mReceiver1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_musicplay);
		initView();

		mp3Infos = MediaUtils.getMp3Infos(this);
		myHandler = new MyHandler(MusicPlayerActivity.this);
		seekBar.setOnSeekBarChangeListener(this);//进度条拖拽
		//绑定服务，此方法在父类中
//		bindplayService();

		//注册关于唤醒机器人的广播
//		mReceiver1 = new WakeBroadcastReceiver1(MusicPlayerActivity.this);
//		IntentFilter filter = new IntentFilter();
//		filter.addAction(Constant.WAKEUPFILTER);
//		registerReceiver(mReceiver1, filter);

		//在sp中记录一下MusicPlayerActivity是不是活着的状态，如果是活着的话，就不用startActivity了
		mSp = getSharedPreferences(Constant.USERCFG, MODE_PRIVATE);
		SharedPreferences.Editor edit = mSp.edit();
		edit.putString(Constant.MUSICPLAYERACTIVITY, "true");
		edit.commit();

		//注册eventbus的订阅者
//		EventBus.getDefault().register(MusicPlayerActivity.this);
	}

	/**
	 * 机器人被唤醒时会触发下面的广播接收者
	 */
	private static class WakeBroadcastReceiver1 extends BroadcastReceiver {

		private final WeakReference<MusicPlayerActivity> mContext;

		public WakeBroadcastReceiver1(MusicPlayerActivity context) {
			mContext = new WeakReference<>(context);
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			MusicPlayerActivity activity = mContext.get();
			if (activity != null) {
				String action = intent.getAction();
				if (Constant.WAKEUPFILTER.equals(action)) {
					KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
					if (event.getKeyCode() == KeyEvent.KEYCODE_NOTIFICATION && event.getAction() == KeyEvent.ACTION_UP) {
						activity.img_play.setImageResource(R.drawable.button_play);
						activity.playService.pause();
						activity.finish();
					}
				}
			}
		}
	}

	private void initView() {
		mRootLayout = (RelativeLayout) findViewById(R.id.player_container);
		title = (TextView) findViewById(R.id.title);
		begin_time = (TextView) findViewById(R.id.begin_time);
		end_time = (TextView) findViewById(R.id.end_time);
		img_play = (ImageButton) findViewById(R.id.begin);
		img_back = (ImageButton) findViewById(R.id.back);
		img_go = (ImageButton) findViewById(R.id.go);
		menu = (ImageButton) findViewById(R.id.menu);
		mBackBtn = (ImageButton) findViewById(R.id.play_button_back);
		//img_lyric=(ImageView) findViewById(R.id.img_lyric);
		//mLrcView = (LrcView) findViewById(R.id.lrcShowView);
		seekBar = (SeekBar) findViewById(R.id.skbProgress);
		img_love = (ImageView) findViewById(R.id.love_music);
		mPlay_more_functions = (ImageButton) findViewById(R.id.play_more_functions);

		mBackBtn.setOnClickListener(this);
		img_play.setOnClickListener(this);
		img_back.setOnClickListener(this);
		img_go.setOnClickListener(this);
		menu.setOnClickListener(this);
		img_love.setOnClickListener(this);
		mPlay_more_functions.setOnClickListener(this);

		//注册来电接收者,监听来电状态，如果来电话了，就退出playActivity
//		IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
//		if (mCallReceiver == null) {
//			mCallReceiver = new NewCallReceiver();
//		}
//
//		registerReceiver(mCallReceiver, callFilter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mIsResume = true;
		String str = getIntent().getStringExtra("str");
bindplayService();
		if (playService != null && playService.ispause()) {
			img_play.setImageResource(R.drawable.button_pause);
		}

		if ("RobotTalk_playMusic".equals(str)) {
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if (playService != null) {
								if (playService.ispause()) {
									img_play.setImageResource(R.drawable.button_pause);
									playService.start();
								} else {
									playService.play(sp.getInt("currentposition", playService.getCurrentPosition()));
								}
							}
						}
					});
				}
			}, 1500);

		}
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mIsResume = false;
unbindplayService();
		hideVolumePopupWindow();
	}


	static class MyHandler extends Handler {
		private final WeakReference<MusicPlayerActivity> mActivity;

		public MyHandler(MusicPlayerActivity activity) {
			mActivity = new WeakReference<>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MusicPlayerActivity activity = mActivity.get();
			if (activity != null) {
				switch (msg.what) {
					case UPDATE_TIME:
						activity.begin_time.setText(MediaUtils.formatTime((long) msg.arg1));
						break;
				}
			}
		}
	}

	@Override
	public void publish(int progress) {
		//实时发生变化的变量
		Message msg = myHandler.obtainMessage(UPDATE_TIME);
		msg.arg1 = progress;
		myHandler.sendMessage(msg);
		seekBar.setProgress(progress);
	}

	@Override
	public void change(int position) {//状态性变量改变
		Mp3Info mp3Info = mp3Infos.get(position);
		//setLrcView();
		Log.e("MusicPlayerActivity", "change: " + mp3Info.getTitle());
		Log.e("MusicPlayerActivity", "change: 位置position" + position);

		title.setText(mp3Info.getTitle());
		end_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));
		if (query(playService.getCurrentPosition())) {
			img_love.setImageResource(R.drawable.keep);//设置如果在收藏db查询的当前播放歌曲的信息返回true则把图标设置为红心
		} else {
			img_love.setImageResource(R.drawable.nokeep);
		}
		Bitmap bm = MediaUtils.getArtwork(this, mp3Info.getId(), mp3Info.getAlbumId(), true, false);
		//img_lyric.setImageBitmap(bm);
		seekBar.setProgress(0);
		seekBar.setMax((int) mp3Info.getDuration());
		if (playService.isplaying()) {
			img_play.setImageResource(R.drawable.button_pause);
//			DemoHelper.getInstance().stopLedTimer();
//			DemoHelper.getInstance().startLedTimer();
		} else {
			img_play.setImageResource(R.drawable.button_play);
//			DemoHelper.getInstance().stopLedTimer();
		}
		switch (playService.getPlay_mode()) {//播放模式，顺序播放，随机播放，单曲循环
			case PlayService.ORDER_PLAY:
				menu.setImageResource(R.drawable.button_playmode_sequential);
				menu.setTag(PlayService.ORDER_PLAY);
				break;
			case PlayService.RANDOM_PLAY:
				menu.setImageResource(R.drawable.button_playmode_shuffle);
				menu.setTag(PlayService.RANDOM_PLAY);
				break;
			case PlayService.SINGLE_PLAY:
				menu.setImageResource(R.drawable.button_playmode_repeat_single);
				menu.setTag(PlayService.SINGLE_PLAY);
		}
	}

	//接收eventbus传递过来的mp3Info，用来更新UI，
//	@Subscribe(threadMode = ThreadMode.MAIN)
//	public void updateUI(Mp3Info mp3Info) {
//		title.setText(mp3Info.getTitle());
//		end_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));
//		if (query(playService.getCurrentPosition())) {
//			img_love.setImageResource(R.drawable.keep);//设置如果在收藏db查询的当前播放歌曲的信息返回true则把图标设置为红心
//		} else {
//			img_love.setImageResource(R.drawable.nokeep);
//		}
//		Bitmap bm = MediaUtils.getArtwork(this, mp3Info.getId(), mp3Info.getAlbumId(), true, false);
//		//img_lyric.setImageBitmap(bm);
//		seekBar.setProgress(0);
//		seekBar.setMax((int) mp3Info.getDuration());
//		if (playService.isplaying()) {
//			img_play.setImageResource(R.drawable.button_pause);
//			DemoHelper.getInstance().stopLedTimer();
//			DemoHelper.getInstance().startLedTimer();
//		} else {
//			img_play.setImageResource(R.drawable.button_play);
//			DemoHelper.getInstance().stopLedTimer();
//		}
//		switch (playService.getPlay_mode()) {//播放模式，顺序播放，随机播放，单曲循环
//			case PlayService.ORDER_PLAY:
//				menu.setImageResource(R.drawable.button_playmode_sequential);
//				menu.setTag(PlayService.ORDER_PLAY);
//				break;
//			case PlayService.RANDOM_PLAY:
//				menu.setImageResource(R.drawable.button_playmode_shuffle);
//				menu.setTag(PlayService.RANDOM_PLAY);
//				break;
//			case PlayService.SINGLE_PLAY:
//				menu.setImageResource(R.drawable.button_playmode_repeat_single);
//				menu.setTag(PlayService.SINGLE_PLAY);
//		}
//	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.play_button_back) {//点击左上角的返回按钮的时候，就跳转到主页
			finish();

			Intent intent = getIntent();
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				mStr = bundle.getString("str");
			}

			if ("RobotTalk_playMusic".equals(mStr)) {
				if (playService.isplaying()) {
					img_play.setImageResource(R.drawable.button_play);
					playService.pause();
					finish();
				}
			} else {
				finish();
			}
		} else if (v.getId() == R.id.begin) {//点击播放按钮的时候
			if (playService.isplaying()) {//如果是正在播放的时候点击了播放按钮，就暂停播放
				img_play.setImageResource(R.drawable.button_play);
//				DemoHelper.getInstance().stopLedTimer();
				playService.pause();
			} else {//否则就播放音乐
				if (playService.ispause()) {
					img_play.setImageResource(R.drawable.button_pause);
					playService.start();
//					DemoHelper.getInstance().stopLedTimer();
//					DemoHelper.getInstance().startLedTimer();
				} else {
					playService.play(sp.getInt("currentposition", playService.getCurrentPosition()));
				}
			}
		} else if (v.getId() == R.id.go) {//点击下一曲的时候
			playService.next();
		} else if (v.getId() == R.id.back) {//点击上一曲的时候
			playService.prev();
		} else if (v.getId() == R.id.menu) {//d点击播放模式按钮的时候，切换顺序播放、单曲循环等
			int mode = (Integer) menu.getTag();
			switch (mode) {
				case PlayService.ORDER_PLAY:
					menu.setImageResource(R.drawable.button_playmode_shuffle);
					menu.setTag(PlayService.RANDOM_PLAY);
					playService.setPlay_mode(PlayService.RANDOM_PLAY);
					ToUtil.showShort(getApplicationContext(), "随机播放已开启");
					break;
				case PlayService.RANDOM_PLAY:
					menu.setImageResource(R.drawable.button_playmode_repeat_single);
					menu.setTag(PlayService.SINGLE_PLAY);
					playService.setPlay_mode(PlayService.SINGLE_PLAY);
					ToUtil.showShort(getApplicationContext(), "单曲循环已开启");
					break;
				case PlayService.SINGLE_PLAY:
					menu.setImageResource(R.drawable.button_playmode_sequential);
					menu.setTag(PlayService.ORDER_PLAY);
					playService.setPlay_mode(PlayService.ORDER_PLAY);
					ToUtil.showShort(getApplicationContext(), "顺序播放已开启");
					break;
			}
		} else if (v.getId() == R.id.love_music) {//点击收藏按钮的时候
			if (query(playService.getCurrentPosition())) {
				delete(playService.getCurrentPosition());
				img_love.setImageResource(R.drawable.nokeep);
				Toast.makeText(this, "取消收藏", Toast.LENGTH_SHORT).show();
			} else {
				add(playService.getCurrentPosition(), mp3Infos.get(playService.getCurrentPosition()).getTitle());
				img_love.setImageResource(R.drawable.keep);
				Toast.makeText(this, "添加收藏", Toast.LENGTH_SHORT).show();
			}
		} else if (v.getId() == R.id.play_more_functions) {//点击右上角的更多功能的按钮时
			showVolumePopupWindow(mRootLayout);
		}
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromuser) {
		//歌曲
		if (fromuser) {
			playService.pause();
			playService.seekTo(progress);
			img_play.setImageResource(R.drawable.button_pause);
			playService.start();
		}

	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
	}

	///////////////////////////////////////////////////////////////////
	//收藏关联sqlitedatabase

	/**
	 * 数据库相关操作，增删改查
	 *
	 * @param mp3id
	 * @param mp3name
	 */
	private void add(int mp3id, String mp3name) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("mp3infoID", mp3id + "");
		values.put("title", mp3name);
		db.insert("mymusic", null, values);
	}

	private void delete(int mp3id) {
		SQLiteDatabase db = helper.getWritableDatabase();
		db.delete("mymusic", "mp3infoID=?", new String[]{mp3id + ""});
		db.close();
	}

	private boolean query(int mp3id) {
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery("select * from mymusic where mp3infoID=?", new String[]{mp3id + ""});
		boolean result = cursor.moveToNext();
		cursor.close();
		db.close();
		return result;
	}
	//////////////////////////////////////歌词部分

	private void setLrcView() {
		try {
			String path = mp3Infos.get(playService.getCurrentPosition()).getUrl().replace(".mp3", ".lrc");
			Log.i("path", "歌词文件路径:" + path);
			File file = new File(path);
			//创建一个文件输入流对象
			InputStream is = new FileInputStream(file);
			//mLrcView.setLrcList(is); // 传入歌词文件流
			showLrc();
			//isInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("setLrcViewException", "异常");
		}
	}

	/**
	 * 没100毫秒传入歌曲播放进度
	 */
	private void showLrc() {
		//	mLrcView.postDelayed(new Runnable() {
		//		@Override
		//		public void run() {
		//			mDuration = playService.getDuration();
		//			int currentPositions = playService.getcurrentpositions();
		//			mLrcView.setIndex(currentPositions, mDuration);
		//			mLrcView.postDelayed(this, 100);
		//		}
		//	}, 100);
	}

	/**
	 * 隐藏音量控制窗口
	 */
	protected void hideVolumePopupWindow() {
		if (null != volumePopupWindow && volumePopupWindow.isShowing()) {
			volumePopupWindow.dismiss();
		}
	}

	protected VolumePopupWindow volumePopupWindow;

	/**
	 * 显示音量控制窗口
	 */
	protected void showVolumePopupWindow(View parent) {
		if (null == volumePopupWindow) {
			View view = LayoutInflater.from(this).inflate(R.layout.volume_popup_window, null);
			volumePopupWindow = new VolumePopupWindow(this, view,
					ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
					false);
			// 需要设置一下此参数，点击外边可消失
			volumePopupWindow.setBackgroundDrawable(new BitmapDrawable());
			//设置点击窗口外边窗口消失
			volumePopupWindow.setOutsideTouchable(true);
			// 设置此参数获得焦点，否则无法点击
			volumePopupWindow.setFocusable(true);
			volumePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
				@Override
				public void onDismiss() {
					volumePopupWindow = null;
				}
			});
		}
		if (null != volumePopupWindow && !volumePopupWindow.isShowing()) {
			final int titleBarHeight = dp2px(this, 96);
			volumePopupWindow.showAtLocation(parent, Gravity.TOP, 0, titleBarHeight);
		}
	}

	public static int dp2px(Context context, float dpVal) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics());
	}

	//广播接收者，接收到广播就暂停播放音乐退出此activity
//	private class NewCallReceiver extends BroadcastReceiver {
//		@Override
//		public void onReceive(Context context, Intent intent) {
//			if (!DemoHelper.getInstance().isLoggedIn()) {
//				return;
//			}
//			finish();
//		}
//	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
//		DemoHelper.getInstance().stopLedTimer();
//		unregisterReceiver(mCallReceiver);
//		unregisterReceiver(mReceiver1);
		//解绑服务
//		unbindplayService();
		//在sp中记录一下MusicPlayerActivity是不是活着的状态，如果是活着的话，就不用startActivity了
		SharedPreferences.Editor edit = mSp.edit();
		edit.putString(Constant.MUSICPLAYERACTIVITY, "false");
		edit.apply();

		//注销eventbus的订阅
//		EventBus.getDefault().unregister(MusicPlayerActivity.this);
	}
}
